package com.socialsoftware.MediaCommunication.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.permissionx.guolindev.PermissionX;
import com.socialsoftware.MediaCommunication.model.CallMode;
import com.socialsoftware.MediaCommunication.model.CommunicationMessage;
import com.socialsoftware.MediaCommunication.model.MessageType;
import com.socialsoftware.MediaCommunication.service.WebSocketService;
import com.socialsoftware.MediaCommunication.utils.Constants;
import com.socialsoftware.MediaCommunication.view.AudioVisualizerView;
import com.socialsoftware.MediaCommunication.view.RippleAnimationView;
import com.socialsoftware.MediaCommunication.webrtc.WebRTCManager;
import com.socialsoftware.R;
import com.socialsoftware.util.AvatarUtil;

import org.json.JSONException;
import org.webrtc.VideoTrack;

/**
 * Activity for audio-only calls
 */
public class AudioChatActivity extends AppCompatActivity implements WebRTCManager.WebRTCListener {
    private static final String TAG = "AudioChatActivity";
    private TextView tvStatus;
    private TextView tvRemoteUser;
    private ImageButton btnHangup;
    private ImageButton btnMute;
    private ImageButton btnSpeaker;
    private ImageView ivAvatar;
    private ImageView ivCallStatus;
    private TextView tvCallDuration;
    private AudioVisualizerView audioVisualizer;
    private RippleAnimationView rippleView;
    private RippleAnimationView callingRippleView;
    private ConstraintLayout callingLayout;
    private TextView tvCallingStatus;
    private TextView tvCalleeName;
    private ImageButton btnCancelCall;
    private WebSocketService webSocketService;
    private WebRTCManager webRTCManager;
    private boolean isWebSocketServiceBound = false;
    private boolean isIncomingCall = false;
    private String targetUser;
    private String targetUsername;
    private boolean isCallConnected = false;
    private boolean isMuted = false;
    private boolean isSpeakerOn = false;
    private AudioManager audioManager;
    private Handler handler = new Handler();
    private final ServiceConnection webSocketServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            isWebSocketServiceBound = true;
            webRTCManager = new WebRTCManager(AudioChatActivity.this, webSocketService, AudioChatActivity.this);
            webRTCManager.setCallMode(CallMode.AUDIO.getValue());
            webRTCManager.init();
            if (isIncomingCall && targetUser != null) {
                showCallUI();
                webRTCManager.answerCall(targetUser, CallMode.AUDIO.getValue());
            } else if (targetUser != null) {
                showCallingUI();
                webRTCManager.startCall(targetUser);
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            webSocketService = null;
            isWebSocketServiceBound = false;
        }
    };
    private final BroadcastReceiver webSocketReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_WEBSOCKET_MESSAGE.equals(intent.getAction())) {
                String messageJson = intent.getStringExtra(Constants.EXTRA_MESSAGE_JSON);
                handleWebSocketMessage(messageJson);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_chat);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        targetUser = getIntent().getStringExtra("contact_username");
        targetUsername = getIntent().getStringExtra("contact_name");
        if (targetUsername == null) {
            targetUsername = targetUser; // 如果没有名称，使用用户名作为显示名称
        }
        isIncomingCall = getIntent().getBooleanExtra("isIncoming", false);
        if (isIncomingCall) {
            targetUser = getIntent().getStringExtra(Constants.EXTRA_CALLER_NAME);
            targetUsername = targetUser; // 对于来电，使用用户名作为显示名称
        }
        initViews();
        checkPermissions();
        setTitle("语音通话");
    }
    private void initViews() {
        tvStatus = findViewById(R.id.tv_call_status);
        tvRemoteUser = findViewById(R.id.tv_remote_user);
        btnHangup = findViewById(R.id.btn_hangup);
        btnMute = findViewById(R.id.btn_mute);
        btnSpeaker = findViewById(R.id.btn_speaker);
        ivAvatar = findViewById(R.id.iv_avatar);
        ivCallStatus = findViewById(R.id.iv_call_status);
        audioVisualizer = findViewById(R.id.audio_visualizer);
        rippleView = findViewById(R.id.ripple_view);
        tvCallDuration = findViewById(R.id.tv_call_duration);
        callingLayout = findViewById(R.id.calling_layout);
        tvCallingStatus = findViewById(R.id.tv_calling_status);
        tvCalleeName = findViewById(R.id.tv_callee_name);
        btnCancelCall = findViewById(R.id.btn_cancel_call);
        callingRippleView = findViewById(R.id.calling_ripple_view);
        findViewById(R.id.et_to_user).setVisibility(View.GONE);
        btnHangup.setOnClickListener(v -> hangup());
        btnCancelCall.setOnClickListener(v -> hangup());
        btnMute.setOnClickListener(v -> toggleMute());
        btnSpeaker.setOnClickListener(v -> toggleSpeaker());
        if (targetUsername != null) {
            tvRemoteUser.setText(targetUsername);
            if (tvCalleeName != null) {
                tvCalleeName.setText(targetUsername);
            }
        }
        if (targetUsername != null) {
            ivAvatar.setImageDrawable(AvatarUtil.getGradientAvatar(this, targetUsername));
            ImageView ivCalleeAvatar = findViewById(R.id.iv_callee_avatar);
            if (ivCalleeAvatar != null) {
                ivCalleeAvatar.setImageDrawable(AvatarUtil.getGradientAvatar(this, targetUsername));
            }
        }
        if (!isIncomingCall) {
            showCallingUI();
        } else {
            showCallUI();
        }
    }
    private void showCallingUI() {
        if (callingLayout != null) {
            callingLayout.setVisibility(View.VISIBLE);
            if (callingRippleView != null) {
                callingRippleView.startRippleAnimation();
            }
        }
        tvStatus.setText("正在呼叫...");
    }
    private void showCallUI() {
        if (callingLayout != null) {
            callingLayout.setVisibility(View.GONE);
        }
        if (rippleView != null) {
            rippleView.startRippleAnimation();
        }
        if (audioVisualizer != null) {
            audioVisualizer.startSimulation();
        }
    }
    private void checkPermissions() {
        PermissionX.init(this)
                .permissions(Constants.REQUIRED_PERMISSIONS)
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        bindWebSocketService();
                        registerWebSocketReceiver();
                    } else {
                        Toast.makeText(this, "需要麦克风权限才能进行语音通话", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
    }
    private void bindWebSocketService() {
        Intent intent = new Intent(this, WebSocketService.class);
        bindService(intent, webSocketServiceConnection, Context.BIND_AUTO_CREATE);
    }
    private void registerWebSocketReceiver() {
        IntentFilter filter = new IntentFilter(Constants.ACTION_WEBSOCKET_MESSAGE);
        LocalBroadcastManager.getInstance(this).registerReceiver(webSocketReceiver, filter);
    }
    private void handleWebSocketMessage(String message) {
        try {
            CommunicationMessage commMessage = CommunicationMessage.fromJson(message);
            String type = commMessage.getType();
            if (MessageType.OFFER.getValue().equals(type)) {
                webRTCManager.handleOffer(commMessage.getSdp(), commMessage.getMode());
            } else if (MessageType.ANSWER.getValue().equals(type)) {
                webRTCManager.handleAnswer(commMessage.getSdp());
            } else if (MessageType.ICE.getValue().equals(type)) {
                webRTCManager.handleIceCandidate(
                        commMessage.getSdpMid(),
                        commMessage.getSdpMLineIndex(),
                        commMessage.getCandidate());
            } else if (MessageType.CALL_BACK.getValue().equals(type)) {
                if ("1".equals(commMessage.getMsg())) {
                    runOnUiThread(() -> {
                        if (tvCallingStatus != null) {
                            tvCallingStatus.setText("正在连接...");
                        }
                    });
                    webRTCManager.createOffer();
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(this, "对方拒绝了通话", Toast.LENGTH_SHORT).show();
                        hangup();
                    });
                }
            } else if (MessageType.HANGUP.getValue().equals(type)) {
                runOnUiThread(() -> {
                    Toast.makeText(this, "对方已挂断", Toast.LENGTH_SHORT).show();
                    hangup();
                });
            }
        } catch (JSONException e) {
            Log.e(TAG, "Failed to parse WebSocket message", e);
        }
    }
    private void toggleMute() {
        if (webRTCManager != null) {
            isMuted = !isMuted;
            webRTCManager.setMicrophoneMute(isMuted);
            btnMute.setImageResource(isMuted ? R.drawable.ic_mic_off : R.drawable.ic_mic);
            if (isMuted) {
                audioVisualizer.release();
            } else {
                audioVisualizer.startSimulation();
            }
        }
    }
    private void toggleSpeaker() {
        if (audioManager != null) {
            isSpeakerOn = !isSpeakerOn;
            audioManager.setSpeakerphoneOn(isSpeakerOn);
            btnSpeaker.setImageResource(isSpeakerOn ? R.drawable.ic_volume_up : R.drawable.ic_volume_down);
        }
    }
    private void hangup() {
        if (webRTCManager != null) {
            webRTCManager.hangup();
        }
        finish();
    }
    @Override
    public void onLocalVideoReady(VideoTrack videoTrack) {}
    @Override
    public void onRemoteVideoReady(VideoTrack videoTrack) {}
    @Override
    public void onCallConnected() {
        runOnUiThread(() -> {
            showCallUI();
            tvStatus.setText("通话中");
            isCallConnected = true;
            long startTime = SystemClock.elapsedRealtime();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isCallConnected && tvCallDuration != null) {
                        long elapsedMillis = SystemClock.elapsedRealtime() - startTime;
                        int seconds = (int) (elapsedMillis / 1000) % 60;
                        int minutes = (int) ((elapsedMillis / (1000 * 60)) % 60);
                        int hours = (int) ((elapsedMillis / (1000 * 60 * 60)) % 24);
                        tvCallDuration.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
                        handler.postDelayed(this, 1000);
                    }
                }
            }, 1000);
            try {
                if (webRTCManager != null && audioVisualizer != null) {
                    audioVisualizer.startSimulation();
                }
            } catch (Exception e) {
                Log.e(TAG, "Failed to link audio visualizer", e);
            }
        });
    }
    @Override
    public void onCallDisconnected() {
        runOnUiThread(() -> {Toast.makeText(this, "通话已结束", Toast.LENGTH_SHORT).show();finish();});}
    @Override
    public void onError(String error) {
        runOnUiThread(() -> {Toast.makeText(this, "通话错误: " + error, Toast.LENGTH_SHORT).show();});}
    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        if (audioVisualizer != null) {
            audioVisualizer.release();
        }
        if (rippleView != null) {
            rippleView.stopRippleAnimation();
        }
        if (callingRippleView != null) {
            callingRippleView.stopRippleAnimation();
        }
        if (webRTCManager != null) {
            webRTCManager.release();
            webRTCManager = null;
        }
        if (isWebSocketServiceBound) {
            unbindService(webSocketServiceConnection);
            isWebSocketServiceBound = false;
        }
        LocalBroadcastManager.getInstance(this).unregisterReceiver(webSocketReceiver);
        super.onDestroy();
    }
} 